import os
import logging
from logging.handlers import RotatingFileHandler
import sys
from config.config import get_config

class Logger:
    """
    日志模块，用于记录系统运行日志
    支持输出到控制台和文件，支持日志轮转
    """
    _instance = None
    _initialized = False
    _loggers = {}

    @classmethod
    def get_instance(cls):
        """
        获取Logger单例
        """
        if cls._instance is None:
            cls._instance = cls()
        return cls._instance

    def __init__(self):
        """
        初始化Logger
        """
        if Logger._initialized:
            return
        
        # 获取日志配置
        config = get_config()
        log_config = config.get("log_config", {})
        
        # 日志级别
        self.log_level_str = log_config.get("log_level", "INFO")
        self.log_level = getattr(logging, self.log_level_str)
        
        # 日志目录和文件
        self.log_dir = log_config.get("log_dir", "logs")
        self.log_file = log_config.get("log_file", "math_plan.log")
        self.log_path = os.path.join(self.log_dir, self.log_file)
        
        # 日志轮转配置
        self.max_bytes = log_config.get("max_bytes", 10 * 1024 * 1024)  # 默认10MB
        self.backup_count = log_config.get("backup_count", 5)  # 默认保留5个备份
        
        # 输出配置
        self.console_output = log_config.get("console_output", True)
        self.file_output = log_config.get("file_output", True)
        
        # 创建日志目录
        if self.file_output and not os.path.exists(self.log_dir):
            os.makedirs(self.log_dir)
        
        # 设置日志格式
        self.formatter = logging.Formatter(
            '%(asctime)s - %(levelname)s - %(name)s - %(filename)s:%(lineno)d - %(funcName)s - %(message)s'
        )
        
        Logger._initialized = True

    def get_logger(self, name):
        """
        获取指定名称的logger
        
        Args:
            name: logger名称，通常使用模块名称
            
        Returns:
            logger实例
        """
        if name in self._loggers:
            return self._loggers[name]
        
        logger = logging.getLogger(name)
        logger.setLevel(self.log_level)
        logger.propagate = False  # 避免日志重复输出
        
        # 清除已有的handlers
        if logger.handlers:
            logger.handlers.clear()
        
        # 添加控制台输出
        if self.console_output:
            console_handler = logging.StreamHandler(sys.stdout)
            console_handler.setFormatter(self.formatter)
            logger.addHandler(console_handler)
        
        # 添加文件输出
        if self.file_output:
            file_handler = RotatingFileHandler(
                self.log_path,
                maxBytes=self.max_bytes,
                backupCount=self.backup_count,
                encoding='utf-8'
            )
            file_handler.setFormatter(self.formatter)
            logger.addHandler(file_handler)
        
        self._loggers[name] = logger
        return logger


def get_logger(name):
    """
    获取logger的便捷函数
    
    Args:
        name: logger名称，通常使用模块名称或__name__
        
    Returns:
        logger实例
    """
    return Logger.get_instance().get_logger(name)
